package crontab

import (
	"context"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"time"

	"github.com/olivere/elastic/v7"
	"github.com/spf13/cast"
)

func InitStatUserDaysRow() {
	var (
		err     error
		sources []models_main.RegSource
		today   = time.Now()
	)

	err = global2.GetR().Model(&models_main.RegSource{}).Find(&sources).Error
	if err != nil {
		global2.Log.Error("InitDaysRow Fans error:", err)
	}

	for _, v := range sources {
		var check int64
		global2.GetR().Model(&models_main.StatUser{}).Where("source_key=? and date=?", v.SourceKey, today.Format("2006-01-02")).Count(&check)
		if check == 0 {
			var initRow = &models_main.StatUser{
				SourceKey:  v.SourceKey,
				SourceName: v.SourceName,
				Date:       today,
			}

			err = global2.GetX().Create(&initRow).Error
			if err != nil {
				global2.Log.Error("InitDaysRow Fans error:", err)
			}
		}
	}
}

// 同步主播到es
func SyncAnchor() {
	args := map[string]interface{}{
		"status":    0,
		"is_anchor": 1,
	}
	users, err := db_main.GetAnchors(args, "online_status asc,regist_time desc", 0, 0, 0)
	if err != nil {
		return
	}
	for _, user := range users {
		termQuery := elastic.NewTermQuery("id", cast.ToString(user.Id))
		searchResult, _ := global2.GetEs().Search().Index(_const.ES_Anchor).Query(termQuery).Do(context.Background())
		if searchResult.TotalHits() < 1 {
			var us models_main.PartUser
			us.NickName = user.NickName
			us.Avatar = user.Avatar
			us.Id = user.Id
			us.VipDate = nil
			_, err := global2.GetEs().Index().Index(_const.ES_Anchor).Id(cast.ToString(us.Id)).BodyJson(us).Do(context.Background())
			if err != nil {
				global2.Log.Errorf("err:%v", err)
				continue
			}
		} else {
			//如果在es中存在,需要更新头像url
			_, err1 := global2.GetEs().UpdateByQuery().Index(_const.ES_Anchor).Query(termQuery).Script(elastic.NewScriptInline("ctx._source.vip_date=null;ctx._source.avatar = '" + user.Avatar + "';ctx._source.nick_name = '" + user.NickName + "'").Lang("painless")).Do(context.Background())
			if nil != err1 {
				global2.Log.Errorf("err:%v", err1)
			}
		}
	}

}
